﻿using MediatR;
using ThreeTeams.API.Application.Command.ProductCommand;
using ThreeTeams.Domain.ThreeTeams.Domain;
using ThreeTeams.ErrorCode;
using ThreeTeams.Infrastructure;

namespace ThreeTeams.API.Application.CommandHandler.ProductCommandHandler
{
    public class GetProductCommandHandler : IRequestHandler<GetProductCommand, ApiResult<ApiPaging<Product>>>
    {
        private readonly IBaseRepository<Product> _productRepository;

        public GetProductCommandHandler(IBaseRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public Task<ApiResult<ApiPaging<Product>>> Handle(GetProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<Product>>();
            var query = _productRepository.GetAll();
            var totalCount = query.Count();
            var pageSize = request.PageSize > 0 ? request.PageSize : 5;
            var pageIndex = request.PageIndex > 0 ? request.PageIndex : 1;
            var totalPage = (int)Math.Ceiling(totalCount / (double)pageSize);
            var productList = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var pagingData = new ApiPaging<Product>
            {
                Data = productList,
                TotalCount = totalCount,
                TotalPage = totalPage
            };

            result.Code = ApiEnum.Ok;
            result.Data = pagingData;

            return Task.FromResult(result);
        }
    }
}
